#include "historydatabridge.h"
#include "../utils/logger.h"
#include <QFileInfo>
#include <QDir>

HistoryDataBridge::HistoryDataBridge(DBManager *dbManager, QObject *parent)
    : QObject(parent), m_dbManager(dbManager)
{
    if (!m_dbManager)
    {
        LOG_ERROR("HistoryDataBridge: DBManager 为空");
    }
}

HistoryDataBridge::~HistoryDataBridge()
{
}

QVariantList HistoryDataBridge::queryHistoryData(int meterId,
                                                 const QString &startTime,
                                                 const QString &endTime)
{
    QVariantList result;

    if (!m_dbManager || !m_dbManager->isConnected())
    {
        QString errorMsg = "数据库未连接";
        LOG_ERROR(errorMsg);
        emit queryError(errorMsg);
        return result;
    }

    // 解析时间
    QDateTime startDateTime = parseDateTime(startTime);
    QDateTime endDateTime = parseDateTime(endTime);

    if (!startDateTime.isValid() || !endDateTime.isValid())
    {
        QString errorMsg = QString("无效的时间格式: %1 - %2").arg(startTime).arg(endTime);
        LOG_ERROR(errorMsg);
        emit queryError(errorMsg);
        return result;
    }

    LOG_INFO(QString("查询历史数据: 电表ID=%1, 时间范围=%2 到 %3")
                 .arg(meterId)
                 .arg(startDateTime.toString("yyyy-MM-dd HH:mm:ss"))
                 .arg(endDateTime.toString("yyyy-MM-dd HH:mm:ss")));

    // 从数据库查询
    QVector<HistoryData> dataList = m_dbManager->queryHistoryData(meterId, startDateTime, endDateTime);

    // 转换为 QVariantList
    for (const HistoryData &data : dataList)
    {
        result.append(historyDataToVariantMap(data));
    }

    LOG_INFO(QString("查询完成，共 %1 条记录").arg(result.size()));
    emit queryCompleted(result.size());

    return result;
}

QVariantList HistoryDataBridge::queryHistoryDataPaged(int meterId,
                                                      const QString &startTime,
                                                      const QString &endTime,
                                                      int offset,
                                                      int limit)
{
    QVariantList result;

    if (!m_dbManager || !m_dbManager->isConnected())
    {
        QString errorMsg = "数据库未连接";
        LOG_ERROR(errorMsg);
        emit queryError(errorMsg);
        return result;
    }

    // 解析时间
    QDateTime startDateTime = parseDateTime(startTime);
    QDateTime endDateTime = parseDateTime(endTime);

    if (!startDateTime.isValid() || !endDateTime.isValid())
    {
        QString errorMsg = QString("无效的时间格式: %1 - %2").arg(startTime).arg(endTime);
        LOG_ERROR(errorMsg);
        emit queryError(errorMsg);
        return result;
    }

    LOG_INFO(QString("分页查询历史数据: 电表ID=%1, offset=%2, limit=%3")
                 .arg(meterId)
                 .arg(offset)
                 .arg(limit));

    // 从数据库查询
    QVector<HistoryData> dataList = m_dbManager->queryHistoryDataPaged(
        meterId, startDateTime, endDateTime, offset, limit);

    // 转换为 QVariantList
    for (const HistoryData &data : dataList)
    {
        result.append(historyDataToVariantMap(data));
    }

    emit queryCompleted(result.size());

    return result;
}

int HistoryDataBridge::getHistoryDataCount(int meterId,
                                           const QString &startTime,
                                           const QString &endTime)
{
    if (!m_dbManager || !m_dbManager->isConnected())
    {
        QString errorMsg = "数据库未连接";
        LOG_ERROR(errorMsg);
        emit queryError(errorMsg);
        return 0;
    }

    // 解析时间
    QDateTime startDateTime = parseDateTime(startTime);
    QDateTime endDateTime = parseDateTime(endTime);

    if (!startDateTime.isValid() || !endDateTime.isValid())
    {
        QString errorMsg = QString("无效的时间格式: %1 - %2").arg(startTime).arg(endTime);
        LOG_ERROR(errorMsg);
        emit queryError(errorMsg);
        return 0;
    }

    int count = m_dbManager->getHistoryDataCount(meterId, startDateTime, endDateTime);
    LOG_INFO(QString("历史数据数量: %1 条").arg(count));

    return count;
}

bool HistoryDataBridge::exportToCSV(int meterId,
                                    const QString &startTime,
                                    const QString &endTime,
                                    const QString &filePath)
{
    if (!m_dbManager || !m_dbManager->isConnected())
    {
        QString errorMsg = "数据库未连接";
        LOG_ERROR(errorMsg);
        emit exportError(errorMsg);
        return false;
    }

    // 解析时间
    QDateTime startDateTime = parseDateTime(startTime);
    QDateTime endDateTime = parseDateTime(endTime);

    if (!startDateTime.isValid() || !endDateTime.isValid())
    {
        QString errorMsg = QString("无效的时间格式: %1 - %2").arg(startTime).arg(endTime);
        LOG_ERROR(errorMsg);
        emit exportError(errorMsg);
        return false;
    }

    // 确保导出目录存在
    QFileInfo fileInfo(filePath);
    QDir dir = fileInfo.absoluteDir();
    if (!dir.exists())
    {
        if (!dir.mkpath("."))
        {
            QString errorMsg = QString("无法创建导出目录: %1").arg(dir.path());
            LOG_ERROR(errorMsg);
            emit exportError(errorMsg);
            return false;
        }
    }

    LOG_INFO(QString("导出CSV: 电表ID=%1, 文件=%2").arg(meterId).arg(filePath));

    // 查询数据
    QVector<HistoryData> dataList = m_dbManager->queryHistoryData(meterId, startDateTime, endDateTime);

    if (dataList.isEmpty())
    {
        QString errorMsg = "没有数据可导出";
        LOG_WARNING(errorMsg);
        emit exportError(errorMsg);
        return false;
    }

    // 打开CSV文件
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QString errorMsg = QString("无法创建文件: %1").arg(filePath);
        LOG_ERROR(errorMsg);
        emit exportError(errorMsg);
        return false;
    }

    QTextStream out(&file);
    out.setCodec("UTF-8");

    // 写入CSV头部（带BOM以便Excel正确识别UTF-8）
    file.write("\xEF\xBB\xBF", 3); // 直接写入UTF-8 BOM字节
    out << QString("电表ID,时间,A相电压(V),B相电压(V),C相电压(V),A相电流(A),B相电流(A),C相电流(A)\n");

    // 写入数据
    for (const HistoryData &data : dataList)
    {
        out << data.meterId << ","
            << data.timestamp.toString("yyyy-MM-dd HH:mm:ss") << ","
            << QString::number(data.ua, 'f', 1) << ","
            << QString::number(data.ub, 'f', 1) << ","
            << QString::number(data.uc, 'f', 1) << ","
            << QString::number(data.ia, 'f', 3) << ","
            << QString::number(data.ib, 'f', 3) << ","
            << QString::number(data.ic, 'f', 3) << "\n";
    }

    file.close();

    LOG_INFO(QString("CSV导出成功: %1, %2 条记录").arg(filePath).arg(dataList.size()));
    emit exportCompleted(filePath, dataList.size());

    return true;
}

QVariantMap HistoryDataBridge::queryHistoryStatistics(int meterId,
                                                      const QString &startTime,
                                                      const QString &endTime)
{
    QVariantMap stats;

    if (!m_dbManager || !m_dbManager->isConnected())
    {
        QString errorMsg = "数据库未连接";
        LOG_ERROR(errorMsg);
        emit queryError(errorMsg);
        return stats;
    }

    // 解析时间
    QDateTime startDateTime = parseDateTime(startTime);
    QDateTime endDateTime = parseDateTime(endTime);

    if (!startDateTime.isValid() || !endDateTime.isValid())
    {
        QString errorMsg = QString("无效的时间格式: %1 - %2").arg(startTime).arg(endTime);
        LOG_ERROR(errorMsg);
        emit queryError(errorMsg);
        return stats;
    }

    LOG_INFO(QString("查询电表 %1 历史统计数据: %2 到 %3")
                 .arg(meterId)
                 .arg(startDateTime.toString("yyyy-MM-dd HH:mm:ss"))
                 .arg(endDateTime.toString("yyyy-MM-dd HH:mm:ss")));

    // 查询数据并手动计算统计信息
    QVector<HistoryData> dataList = m_dbManager->queryHistoryData(meterId, startDateTime, endDateTime);

    if (dataList.isEmpty())
    {
        LOG_WARNING("未查询到数据");
        return stats;
    }

    // 初始化统计变量
    double maxVoltage = 0.0, minVoltage = 999999.0;
    double maxCurrent = 0.0, minCurrent = 999999.0;
    double maxPower = 0.0, minPower = 999999.0;
    double sumVoltage = 0.0, sumCurrent = 0.0, sumPower = 0.0;

    // 遍历数据计算统计信息
    for (const HistoryData &data : dataList)
    {
        double avgVoltage = (data.ua + data.ub + data.uc) / 3.0;
        double avgCurrent = (data.ia + data.ib + data.ic) / 3.0;
        double power = data.ua * data.ia + data.ub * data.ib + data.uc * data.ic;

        maxVoltage = qMax(maxVoltage, avgVoltage);
        minVoltage = qMin(minVoltage, avgVoltage);
        maxCurrent = qMax(maxCurrent, avgCurrent);
        minCurrent = qMin(minCurrent, avgCurrent);
        maxPower = qMax(maxPower, power);
        minPower = qMin(minPower, power);

        sumVoltage += avgVoltage;
        sumCurrent += avgCurrent;
        sumPower += power;
    }

    int count = dataList.size();

    // 构建统计结果
    stats["count"] = count;
    stats["maxVoltage"] = maxVoltage;
    stats["minVoltage"] = minVoltage;
    stats["avgVoltage"] = sumVoltage / count;
    stats["maxCurrent"] = maxCurrent;
    stats["minCurrent"] = minCurrent;
    stats["avgCurrent"] = sumCurrent / count;
    stats["maxPower"] = maxPower;
    stats["minPower"] = minPower;
    stats["avgPower"] = sumPower / count;

    LOG_INFO(QString("统计数据查询成功: 最大电压=%1V, 最小电压=%2V, 最大电流=%3A")
                 .arg(maxVoltage, 0, 'f', 1)
                 .arg(minVoltage, 0, 'f', 1)
                 .arg(maxCurrent, 0, 'f', 2));

    return stats;
}

QVariantMap HistoryDataBridge::historyDataToVariantMap(const HistoryData &data)
{
    QVariantMap map;
    map["meterId"] = data.meterId;
    map["ua"] = data.ua;
    map["ub"] = data.ub;
    map["uc"] = data.uc;
    map["ia"] = data.ia;
    map["ib"] = data.ib;
    map["ic"] = data.ic;
    map["timestamp"] = data.timestamp;
    return map;
}

QDateTime HistoryDataBridge::parseDateTime(const QString &timeStr)
{
    // 尝试多种格式
    QDateTime dt = QDateTime::fromString(timeStr, "yyyy-MM-dd HH:mm:ss");
    if (dt.isValid())
    {
        return dt;
    }

    dt = QDateTime::fromString(timeStr, "yyyy-MM-dd");
    if (dt.isValid())
    {
        return dt;
    }

    dt = QDateTime::fromString(timeStr, Qt::ISODate);
    if (dt.isValid())
    {
        return dt;
    }

    LOG_WARNING(QString("无法解析时间字符串: %1").arg(timeStr));
    return QDateTime();
}
